﻿using System.Collections.Generic;
using System.Text;

namespace Twitter
{
    /// <summary>
    /// MessageBuilder for list kind messages.
    /// Appended fragments with <see cref="ListMessageBuilder.AppendFragment"/> are never splitted.
    /// </summary>
    public class ListMessageBuilder : IMessageBuilder
    {
        private const int DefaultPreferredMessageSize = 110;

        List<string> fragments;
        int preferredMessageSize;

        public ListMessageBuilder()
            : this(DefaultPreferredMessageSize)
        {
        }

        public ListMessageBuilder(int preferredMessageSize)
        {
            this.fragments = new List<string>();
            this.preferredMessageSize = preferredMessageSize;
        }

        public void Clear()
        {
            fragments.Clear();
        }

        public void AppendFragment(string fragment)
        {
            fragments.Add(fragment);
        }

        public IEnumerable<string> GetMessages()
        {
            StringBuilder buffer = new StringBuilder();
            foreach (string fragment in fragments)
            {
                if (ShouldAppendFragment(buffer, fragment))
                {
                    buffer.Append(fragment);
                }
                else
                {
                    yield return buffer.ToString();
                    buffer = new StringBuilder();
                    buffer.Append(fragment);
                }
            }
            if (buffer.Length > 0)
                yield return buffer.ToString();
        }

        private bool ShouldAppendFragment(StringBuilder buffer, string fragment)
        {
            return buffer.Length == 0 || buffer.Length + fragment.Length <= preferredMessageSize;
        }
    }
}
